package com.by.log.entity;

import com.by.log.constants.LogLevel;
import lombok.Data;
import lombok.ToString;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 日志实体类，包含完整的日志元数据
 */
@Data
@ToString(exclude = "throwable")
public class LogEntry {
    /** 日志唯一标识 */
    private String logId = UUID.randomUUID().toString();

    /** 服务名称 */
    private String serviceName;

    /** 日志级别 */
    private LogLevel level;

    /** 日志内容 */
    private String message;

    /** 异常堆栈信息 */
    private String throwable;

    /** 时间戳 */
    private LocalDateTime timestamp = LocalDateTime.now();

    /** 链路追踪ID */
    private String traceId;

    /** 跨度ID */
    private String spanId;

    /** 父跨度ID */
    private String parentSpanId;

    /** 类名 */
    private String className;

    /** 方法名 */
    private String methodName;

    /** 线程信息 */
    private String threadName;
    private Long threadId;

    /** 网络信息 */
    private String localIp;
    private String remoteIp;

    /** 方法执行时间（毫秒） */
    private Long executionTime;

    /** 是否成功 */
    private Boolean success;

    /** 扩展字段 */
    private Map<String, Object> extendedFields = new HashMap<>();

    public LogEntry() {
        this.threadName = Thread.currentThread().getName();
        this.threadId = Thread.currentThread().getId();
    }

    public void addExtendedField(String key, Object value) {
        this.extendedFields.put(key, value);
    }
    
    /**
     * 从追踪上下文填充追踪信息
     * @param traceContext 追踪上下文
     */
    public void populateFromTraceContext(com.by.log.TraceContext traceContext) {
        if (traceContext != null) {
            this.traceId = traceContext.getTraceId();
            this.spanId = traceContext.getSpanId();
            this.parentSpanId = traceContext.getParentSpanId();
        }
    }
}